package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.GlobalConstant;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.ICategoryService;
import com.itheima.service.IDishFlavorService;
import com.itheima.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 菜品控制器
 *
 * @author hua
 * @since 2022/11/4 20:49
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
@Autowired
    private IDishService dishService;
@Autowired
private  ICategoryService categoryService;
@Autowired
private IDishFlavorService dishFlavorService;
@Autowired
private RedisTemplate<Object,Object> redisTemplate;
//接受前端的请求
    //定义接口
    //1. 请求路径
    //2. 请求方式
    //3. 请求参数
    //4. 返回值
@PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
    log.info("前后端连通");
    dishService.saveWithFlavor(dishDto);
    String key="dish:"+dishDto.getCategoryId()+":"+ dishDto.getStatus();
    redisTemplate.delete(key);
    return R.success(GlobalConstant.SUCCESS);
}
/**
 * 分页查询
 */
@GetMapping("/page")
    public R<Page<DishDto>> getPage(Integer page,Integer pageSize,String name){
    log.info("前后端连通");
    //1.构造分页条件对象
    Page<Dish> queryPage = new Page<>();
    //当前页
    queryPage.setCurrent(page);
    //当前页要显示多少行
    queryPage.setSize(pageSize);
    //2.构建查询及排序条件
    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
    //name查询条件
    //where name like '%name%'
    queryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
    //根据修改时间倒序
    //主要是用户体验方面的考虑
    queryWrapper.orderByDesc(Dish::getUpdateTime);
    //3.执行分页条件查询
    Page<Dish> dishPage=this.dishService.page(queryPage,queryWrapper);
    //4.构建返回结果对象,并copy查询结果到该对象中
    Page<DishDto> result = new Page<>();
    //dishPage ->result
    BeanUtils.copyProperties(dishPage,result,"records");
    //5.遍历分页查询列表数据,把Dish对象转化为DIshDto对象,同时赋值分类名称
    //这里存放的是我们所有要返回的数据
    ArrayList<DishDto> records = new ArrayList<>();
    for (Dish dish: dishPage.getRecords()) {
        DishDto dishDto = new DishDto();
        //dish ->dishDto
        BeanUtils.copyProperties(dish,dishDto);
        //查询分类
        Category category=this.categoryService.getById(dish.getCategoryId());
        if (category !=null){
            //给分类名称赋值
            dishDto.setCategoryName(category.getName());
        }
    records.add(dishDto);
    }
    //6.封装数据并返回
    result.setRecords(records);
    return R.success(result);

}
/**
 * 根据Id查询相应的菜品信息
 */
@GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable long id){
    log.info("前后端连通");
//来完成getBYIdWithFlavor方法
    DishDto dishDto = this.dishService.getBYIdWithFlavor(id);
    return R.success(dishDto);
}
/**
 * 更新菜品数据
 */
@PutMapping
    public R<DishDto> update(@RequestBody DishDto dish){
    //前后端联通
    log.info("前后端联通");
    this.dishService.updateWithFlavor(dish);
    Set keys=redisTemplate.keys("dish:*");
    redisTemplate.delete(keys);
    return R.success(dish);
}
/**
 * 新增菜品
 */
//@GetMapping("/list")
//    public R<List<Dish>> getList(Dish dish){
//    //判断如果没有传入的参数,抛出异常
//    if (dish ==null){
//        throw new CustomException("菜品查询失败");
//    }
//    //根据菜品分类id查询菜品
//    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//    //菜品分类
//    queryWrapper.eq(dish.getCategoryId() !=null,Dish::getCategoryId,dish.getCategoryId());
//    //查询起售状态的菜品,1:起售, 0:停售
//    queryWrapper.eq(Dish::getStatus,1);
//    List<Dish> list = this.dishService.list(queryWrapper);
//    return R.success(list);
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //先从redis中获取菜品数据
        //最终要返回的数据
        List<DishDto> dishDtoList;
        //key
        String key="dish:"+dish.getCategoryId()+":"+ dish.getStatus();
        //查询redis中是否参在这个key相应的数据
         dishDtoList= (List<DishDto>)this.redisTemplate.opsForValue().get(key);
         //判断dishDtoList是否为null
        //如果要是存在数据的话,也就是不为null的情况,那么直接返回
         if (dishDtoList !=null){
             return R.success(dishDtoList);
         }
         //如果要是缓存中不存在数据,缓存未命中,那么要查询数据库
        dishDtoList=new ArrayList<>();
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        //region foreach写法
//        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish item : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }
        //endregion
        //region Lambda使用Map方法的写法
        //        List<DishDto> dishDtoList = list.stream().map((item) -> {
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item,dishDto);
//            Long categoryId = item.getCategoryId();//分类id
//            //根据id查询分类对象
//            Category category = categoryService.getById(categoryId);
//            if(category != null){
//                String categoryName = category.getName();
//                dishDto.setCategoryName(categoryName);
//            }
//            //当前菜品的id
//            Long dishId = item.getId();
//            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
//            //SQL:select * from dish_flavor where dish_id = ?
//            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
//            dishDto.setFlavors(dishFlavorList);
//            return dishDto;
//        }).collect(Collectors.toList());
        //endregion
        //数据产生之后,在写到redis中,写到缓存中
        //在写缓存的时候会加一个过期时间
        //这个其实是一个保底操作
        //能保证如果某些特殊情况,再新增或者修改的时候,没有成功的删除掉缓存
        //一个显示之后,也就是指缓存的过期时间到了之后,能让数据库跟缓存保存一致
        //往往我们在做缓存操作的时候,都会设置一个过期事件的原因
        this.redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}